<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>后台管理 - 菜单管理</title>
  <!-- Vue.js -->
  <script src="/js/vue.js"></script>
  <!-- Element UI CSS -->
  <link type="text/css" rel="stylesheet" href="/css/index.css">
  <!-- Element UI JS -->
  <script src="/js/index.js"></script>
  <!-- Axios -->
  <script src="/js/axios.min.js"></script>
  <style>
    .main-container {
      padding: 20px;
      background-color: #f5f7fa;
      min-height: 600px;
      border-radius: 8px;
      margin-right: 100px;
    }
    .form-title {
      font-size: 18px;
      color: #303133;
      margin-bottom: 20px;
    }
    /*.btn-group {*/
    /*  display: flex;*/
    /*  gap: 10px;*/
    /*  margin-top: 20px;*/
    /*}*/
    .action-buttons {
      display: flex;
      gap: 8px;
      justify-content: left;
    }
    .el-form-item__label {
      font-weight: bold;
    }

  </style>
</head>
<body>
<div id="app">
  <el-container style="height: 500px; border: 1px solid #eee">
    <el-aside width="200px" style="background-color: rgb(238, 241, 246)">
      <el-tree
              :data="data"
              :props="defaultProps"
              @node-click="handleNodeClick"
              node-key="id"
              default-expand-all
              highlight-current
              @current-change="handleCurrentChange">
      </el-tree>
    </el-aside>

    <el-container>
<!--      <el-header style="text-align: left; font-size: 12px">-->
<!--        <el-row type="flex" justify="end" align="middle" style="height: 100%;">-->
<!--          <el-col>-->
<!--            <el-button-->
<!--                    type="primary"-->
<!--                    icon="el-icon-refresh"-->
<!--                    @click="refreshPage"-->
<!--                    size="small"-->
<!--                    style="background-color: #409EFF; border-color: #409EFF;">-->
<!--              刷新-->
<!--            </el-button>-->
<!--          </el-col>-->
<!--        </el-row>-->
<!--      </el-header>-->

      <el-main>
        <div class="main-container">
          <!--          添加显示：添加界面，点击树状menu显示：编辑/删除界面-->
          <div class="form-title">{{ isEditing ? '编辑/删除菜单' : '添加菜单' }}</div>

          <!-- 操作按钮区 -->
          <div class="action-buttons">
<!--            <div class="btn-group">-->
            <el-button
                    type="primary"
                    @click="ToAddMode"
                    v-if="isEditing"
            >
              返回添加
            </el-button>
            <el-button type="danger" @click="deleteMenu" v-if="currentMenu">删除菜单</el-button>
          </div>

          <!-- 表单区域 -->
          <el-form :model="form" label-width="100px" style="width: 500px; margin: 30px auto;" ref="formRef" :rules="rules">
            <el-form-item label="菜单名称" prop="menuName">
              <el-input v-model="form.menuName" placeholder="请输入菜单名称"></el-input>
            </el-form-item>

            <el-form-item label="父节点" prop="parentName">
              <el-input
                      v-model="form.parentName"
                      placeholder="请选择父节点"
                      @focus="showParentTree"
                      readonly
                      suffix-icon="el-icon-arrow-down"
                      style="cursor: pointer;">
              </el-input>

              <el-dialog
                      title="选择父节点"
                      :visible.sync="parentDialogVisible"
                      width="500px"
                      @close="handleParentClose">
                <!-- 标题区域使用 slot="title" -->
                <span slot="title">
                        选择父节点
                      <el-button type="text" size="small" @click="setAsRootMenu" style="margin-left: 10px;">
                        设为一级菜单
                      </el-button>
                      </span>

                <el-tree
                        ref="parentTree"
                        :data="parentTreeData"
                        show-checkbox
                        node-key="id"
                        default-expand-all
                        :props="defaultProps"
                        :check-strictly="true"
                        @check-change="handleParentCheckChange">
                </el-tree>

                <!--                &lt;!&ndash; 新增：设为一级菜单按钮 &ndash;&gt;-->
                <!--                <div style="margin-top: 10px; text-align: center;">-->
                <!--                  <el-button type="text" @click="setAsRootMenu" size="small">-->
                <!--                    设为一级菜单-->
                <!--                  </el-button>-->
                <!--                </div>-->

                <span slot="footer" class="dialog-footer">
                  <el-button @click="parentDialogVisible = false">取 消</el-button>
                  <el-button type="primary" @click="confirmParentSelection">确 定</el-button>
                </span>
              </el-dialog>
            </el-form-item>

            <el-form-item label="请求地址" prop="url">
              <el-input v-model="form.url" placeholder="请输入请求地址"></el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submitForm">保存</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-main>
    </el-container>
  </el-container>
</div>

<script>
  new Vue({
    el: "#app",
    data() {
      return {
        data: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        form: {
          menuId: '',
          menuName: '',
          parentId: '',
          parentName: '',
          url: ''
        },
        currentMenu: null,
        parentDialogVisible: false,
        parentTreeData: [],
        selectedParentKeys: [],
        isEditing: false, // 是否处于编辑状态
        rules: {
          menuName: [
            { required: true, message: '请输入菜单名称', trigger: 'blur' },
            { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
          ],
          // parentName: [
          //   { required: true, message: '请选择父节点', trigger: 'change' }
          // ],
          // url: [
          //   { required: true, message: '请输入请求地址', trigger: 'blur' },
          //   { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
          // ]
        }
      }
    },

    created() {
      this.loadMenuTree();
    },

    methods: {
      refreshPage() {
        location.reload();
      },

      loadMenuTree() {
        axios.get('/menu/queryAllTreeData')
                .then(res => {
                  if (res.data.code === 200) {
                    this.data = res.data.data;
                  }
                })
                .catch(err => {
                  console.error('加载菜单失败:', err);
                });
      },

      handleNodeClick(data) {///菜单点击事件
        console.log('进入编辑-----编写完点提交');
        console.log("菜单点击事件数据/编辑菜单："+data);
        // JSON.stringify 将对象转换成json字符串
        console.log(JSON.stringify(data));
        this.currentMenu = data;
        this.form.menuId = data.id;
        this.form.menuName = data.label;
        this.form.url = data.url;
        this.form.parentId = data.parentId || '';
        this.form.parentName = data.parentLabel || '';
        this.isEditing = true;
        // 清除验证状态
        this.$refs.formRef.clearValidate();
      },

      handleCurrentChange(node) {
        this.currentMenu = node;// 当前选中的菜单
      },


      ToAddMode() {
        // if (this.isEditing) {
          this.isEditing = false;
          this.resetForm();
          this.currentMenu = null;
          this.form.menuId = '';
          this.form.menuName = '';
          this.form.parentId = '';
          this.form.parentName = '';
          this.form.url = '';
          // 清除验证状态
          this.$refs.formRef.clearValidate();
          console.log('进入添加-----添加完写完点提交');
      },

      deleteMenu() {
        if (!this.currentMenu) return;

        this.$confirm(`确定要删除菜单 "${this.currentMenu.label}" 吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 使用箭头函数保持this上下文
          return axios.delete(`/menu/deleteById?menuId=${this.currentMenu.id}`)
                  .then(res => {
                    // 先检查响应是否有效
                    if (!res || !res.data) {
                      throw new Error('无效的响应数据');
                    }

                    console.log('要删除的菜单id:', this.currentMenu.id);

                    if (res.data.code === 200) {
                      this.$message.success('删除成功');
                      this.loadMenuTree(); // 刷新树
                      //返回添加
                      this.ToAddMode();
                    } else {
                      this.$message.error(res.data.message || '删除失败');
                      this.$refs.formRef.clearValidate();
                    }
                  })
                  .catch(err => {
                    console.error('删除失败:', err);
                    this.$message.error('网络错误或处理失败');
                    // 抛出错误，让外层catch处理
                    throw err;
                  });
        }).catch((err) => {
          // 只有当用户真正取消时才显示此消息
          if (err !== 'cancel') {
            this.$message.info('已取消删除');
          }
        });
      },

      showParentTree() {
        this.parentDialogVisible = true;
        this.loadParentTreeData();
      },

      loadParentTreeData() {
        axios.get('/menu/queryAllTreeData')
                .then(res => {
                  if (res.data.code === 200) {
                    this.parentTreeData = res.data.data;
                  }
                })
                .catch(err => {
                  console.error('加载父节点失败:', err);
                });
      },

      handleParentCheckChange(data, checked, indeterminate) {
        if (checked) {
          this.selectedParentKeys.push(data.id);
        } else {
          const index = this.selectedParentKeys.indexOf(data.id);
          if (index > -1) {
            this.selectedParentKeys.splice(index, 1);
          }
        }
      },

      confirmParentSelection() {
        const checkedNodes = this.$refs.parentTree.getCheckedNodes();
        if (checkedNodes.length > 0) {
          this.form.parentName = checkedNodes[0].label;
          this.form.parentId = checkedNodes[0].id;
          this.parentDialogVisible = false;
        } else {
          this.$message.warning('请至少选择一个父节点');
        }
      },

      handleParentClose() {
        this.selectedParentKeys = [];
      },

      submitForm() {
        this.$refs.formRef.validate(valid => {
          if (valid) {
            // 统一使用 POST 请求，根据 isEditing 判断 URL
            const url = this.isEditing ? '/menu/edit' : '/menu/add';

            // 构造完整的 menu 对象
            const menuData = {
              menuId: this.form.menuId,
              menuName: this.form.menuName,
              parentId: this.form.parentId,
              url: this.form.url,
              menuType: 'M', // 默认类型
              visible: '0',  // 默认可见
              icon: '',
              orderNum: 0,
              perms: '',
              remark: ''
            };
            console.log('提交的menuId:', this.form.menuId);
            axios.post(url, menuData)
                    .then(res => {
                      if (res.data.code === 200) {
                        this.$message.success(this.isEditing ? '更新成功' : '添加成功');
                        this.loadMenuTree();
                        //返回添加
                        this.ToAddMode();
                      } else {
                        // this.$message.error(this.isEditing ? '更新失败' : '添加失败');
                        this.$message.error(this.isEditing ?(res.data.message || '更新失败') : '添加失败');
                        this.$refs.formRef.clearValidate();
                      }
                    })
                    .catch(err => {
                      console.error('提交失败:', err);
                      this.$message.error('网络错误');
                    });
          }
        });
      },

      resetForm() {
        if (this.currentMenu&&this.isEditing) {
          this.form.menuId = this.currentMenu.id;
          this.form.menuName = this.currentMenu.label;
          this.form.url = this.currentMenu.url;
          this.form.parentId = this.currentMenu.parentId || '';
          this.form.parentName = this.currentMenu.parentLabel || '';
          //打印
          console.log('要重置编辑的菜单id:', this.currentMenu.id);

        } else {
          // 添加操作时，清空表单
          this.$nextTick(() => {
            // 清空表单
            this.$refs.formRef.resetFields();
            //打印信息
            console.log('添加重置清空表单数据:bbb');
          })
          };

        // 重新验证表单
        this.$nextTick(() => {
          // 清除验证状态
          this.$refs.formRef.clearValidate();
          //打印信息
          console.log('清除菜单验证状态:yyy');
        })
      },

      setAsRootMenu() {
        this.form.parentId = 0;
        this.form.parentName = '';
        this.parentDialogVisible = false; // 关闭弹窗
      }


    }
  });
</script>
</body>
</html>
